package threadjuc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/27 17:01
 * 生产者消费者 lock版
 */
public class Juc5 {
    public static void main(String[] args) {
        //线程都操作资源
        Nums nums = new Nums();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    nums.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    nums.reduce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    nums.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    nums.reduce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
class Nums {
    private int num = 0;
    /**
     * 创建锁
     */
    Lock lock = new ReentrantLock();
    /**
     * 创建监视器
     */
    Condition condition = lock.newCondition();

    public void add() throws InterruptedException {
        lock.lock();
        try{
            //不使用if判断 会出现虚假唤醒
            while (num != 0) {
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "--->" + num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }

    public void reduce() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0) {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "--->" + num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

